package com.qupai.service.impl;

import com.qupai.domain.entity.Auction;
import com.qupai.domain.vo.AuctionEndVO;
import com.qupai.mapper.AuctionMapper;
import com.qupai.service.IHostService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;
import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class HostServiceImpl implements IHostService {

    private final AuctionMapper auctionMapper;

    @Override
    public Auction start(Long auctionId) {
        Auction auction = Auction.builder()
                .id(auctionId)
                .status(2)
                .startTime(LocalDateTime.now()) //更新开始时间
                .build();
        auctionMapper.updateById(auction);
        return auction;
    }

    @Override
    public AuctionEndVO end(Long auctionId) {

        //拿到拍卖会的信息
        Auction auction = auctionMapper.selectById(auctionId);
        LocalDateTime startTime = auction.getStartTime();
        //获得当前时间
        LocalDateTime now = LocalDateTime.now();
        //计算拍卖会的时间差,分别转为时分秒 hour (Long) ......
        // 计算拍卖会的时间差
        Duration duration = Duration.between(startTime, now);

        // 转换为小时、分钟和秒
        Long hours = duration.toHours();
        Long minutes = duration.toMinutes() % 60;
        Long seconds = duration.getSeconds() % 60;

        //更新数据库状态
        auction.setStatus(3);
        auction.setEndTime(now); //更新结束时间
        auctionMapper.updateById(auction);

        //封装返回对象
        AuctionEndVO auctionEndVO=new AuctionEndVO();
        auction=auctionMapper.selectById(auctionId);
        BeanUtils.copyProperties(auction,auctionEndVO);
        auctionEndVO.setHours(hours);
        auctionEndVO.setMinutes(minutes);
        auctionEndVO.setSeconds(seconds);
        return auctionEndVO;

    }
}
